package com.xyy.saas.payment.util;

import com.xyy.util.Base64Util;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.util.FileSystemUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @author wangtianqi
 * @date 2020/12/18 14:33
 */
public class PicUtil {

    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(PicUtil.class);

    private static final String directoryName = "account";
    private static final String filePath = System.getProperty("user.home") + "/pay/";
    public static final String downloadFilePath = System.getProperty("user.home") + "/download/";
    private static final String zipFilePath = System.getProperty("user.home") + "/pay/" + directoryName + "/";

    /**
     * 图片大小修改
     * @param picBytes
     * @param picType jpg \ png
     * @return
     */
    public static String resizeImg(byte[] picBytes, String picType) {
        Long begin = System.currentTimeMillis();
        String basePic = Base64Util.Bytes2Base64(picBytes);
        int length = basePic.length();
        LOGGER.info("PicUtil#resizeImg pic length:{} ", length);
        double scale = 0.8;
        if(length >= 200000) {
            scale = 0.5;
        }
        if(length >= 1000000) {
            scale = 0.3;
        }
        String zipPic = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            BufferedImage src = bytes2BufferedImg(picBytes);
            BufferedImage out = Thumbnails.of(src).scale(scale).asBufferedImage();
            ImageIO.write(out, picType, byteArrayOutputStream);
            zipPic = Base64Util.Bytes2Base64(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            LOGGER.error("PicUtil#resizeImg resize error", e);
        } finally {
            IOUtils.closeQuietly(byteArrayOutputStream);
        }
        if(StringUtils.isEmpty(zipPic)) {
            zipPic = basePic;
        }
        LOGGER.info("PicUtil#resizeImg pic length:{} after:{} time:{}", length, zipPic.length(), System.currentTimeMillis() - begin);
        return zipPic;
    }


    public static BufferedImage bytes2BufferedImg(byte[] picBytes) {
        BufferedImage img = null;
        InputStream inputStream = new ByteArrayInputStream(picBytes);
        try {
            img = ImageIO.read(inputStream);
        } catch (Exception e) {
            LOGGER.error("PicUtil#bytes2BufferedImg parse pic error", e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return img;
    }

    /**
     * 1.重命名图片
     * 2.压缩图片
     * 3.转成base64
     * @param pics key -> value
     *             图片名 -> URL地址
     * @return
     */
    public static String toZiP(Map<String, String> pics, String accountId) {
        //check file path
        checkFilePath(accountId);
        //download file from fastFdfs into file path
        List<File> srcFiles = downloadFile(pics, accountId);
        //File to Zip
        return ZipToBase64.toBase64Zip(srcFiles);
    }

    /**
     * 下载文件
     */
    public static File toLocalFile(String url, String accountId) {
        // check file path
        checkFilePath(accountId);

        // download file from fastFdfs into file path
        Map<String, String> pics = new HashMap<>();
        pics.put(UUID.randomUUID().toString(), url);
        List<File> srcFiles = downloadFile(pics, accountId);

        // response
        return srcFiles.get(NumberUtils.INTEGER_ZERO);
    }

    private static void checkFilePath(String accountId){
        File file = new File(filePath + accountId + "/");
        //if absent then create
        if(!file .exists()){
            file.mkdirs();
        }
        //if non exist then delete first else create
        else{
            FileSystemUtils.deleteRecursively(file);
            file.mkdirs();
        }
    }

    public static void createFilePath(String filePath) {
        File file = new File(filePath);

        //if absent then create
        if(!file .exists()){
            file.mkdirs();
        }
    }

    private static List<File> downloadFile(Map<String, String> pics, String accountId) {
        if(pics == null){
            return null;
        }
        List<File> srcFiles = new ArrayList<>();
        for(Map.Entry<String, String> entry : pics.entrySet()){
            String fileName = entry.getKey();
            String picUrl = entry.getValue();
            byte[] picBytes = HttpClientUtil.getStream(picUrl);
            FileOutputStream fileOutputStream = null;
            try {
                File file = new File(filePath + accountId + "/" + fileName + ".jpg");
                fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(picBytes);
                srcFiles.add(file);
            } catch (Exception e) {
                LOGGER.error("create local file error ", e);
            }finally {
                if(fileOutputStream != null){
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        //noop
                    }
                }
            }
        }
        return srcFiles;
    }

    /**
     * 通过URL 获取 网络图片流
     *
     * @param url
     * @return
     */
    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取图片格式
     * @param url
     * @return pdf、bmp、jpeg、img、jpg、png
     */
    public static String parsePicType(String url) {
        if(StringUtils.isBlank(url)) {
            return "jpg";
        }

        try {
            int startIndexOf = url.lastIndexOf(".") + NumberUtils.INTEGER_ONE;
            int endIndexOf = url.contains("?") ? url.lastIndexOf("?") : url.length();
            return url.substring(startIndexOf, endIndexOf);
        }
        // pdf、bmp、jpeg、jpg、png
        catch(Exception ex) {
            LOGGER.error("url:" + url + ", error" + ex.getMessage() ,ex);

            if(url.contains("jpg")) {
                return "jpg";
            }
            else if(url.contains("jpeg")) {
                return "jpeg";
            }
            else if(url.contains("png")) {
                return "png";
            }
            else if(url.contains("pdf")) {
                return "pdf";
            }
            else if(url.contains("bmp")) {
                return "bmp";
            }

            return "jpg";
        }
    }

    public static void main(String[] args) {
        System.out.println(parsePicType("https://upload.test.ybm100.com/G2/M00/21/42/Cgo01GJOuyCAJzAiAACccKnQ_Zk517.png"));
    }
}
